<template>
  <div class="market-manage">
    <div class="header">
      <el-page-header @back="handleBack">
        <template #content>
          <span class="text-large font-600 mr-3">订单管理</span>
        </template>
      </el-page-header>
    </div>

    <div class="content">
      <el-card>
        <!-- 搜索和筛选区域 -->
        <template #header>
          <div class="table-header">
            <span>订单列表</span>
            <el-button type="primary" text :icon="Refresh" @click="loadOrders">
              刷新
            </el-button>
          </div>
          
          <div class="search-filter-row">
            <el-form :model="searchForm" :inline="true" class="search-form">
              <el-form-item label="关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="订单ID/商品/用户"
                  clearable
                  style="width: 180px"
                />
              </el-form-item>
              
              <el-form-item label="订单状态">
                <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 120px">
                  <el-option label="待审核" :value="1" />
                  <el-option label="审核通过" :value="2" />
                  <el-option label="审核不通过" :value="0" />
                  <el-option label="已完成" :value="3" />
                  <el-option label="已取消" :value="4" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handleSearch" :icon="Search">
                  搜索
                </el-button>
                <el-button @click="handleReset" :icon="RefreshLeft">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </template>

        <!-- 订单表格 -->
        <el-table
          :data="orderList"
          v-loading="loading"
          border
          style="width: 100%"
          empty-text="暂无订单数据"
        >
          <el-table-column type="expand" width="50">
            <template #default="props">
              <div class="order-detail">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="商品信息">
                    <div class="goods-info">
                      <el-image 
                        v-if="getGoodsImage(props.row.good)"
                        :src="getGoodsImage(props.row.good)" 
                        alt="商品图片"
                        class="goods-image"
                        fit="cover"
                        :preview-src-list="getGoodsPreviewImages(props.row.good)"
                      >
                        <template #error>
                          <div class="image-error">
                            <el-icon><Picture /></el-icon>
                            <span>图片加载失败</span>
                          </div>
                        </template>
                      </el-image>
                      <div class="goods-desc">
                        <p><strong>{{ props.row.good?.title || '未知商品' }}</strong></p>
                        <p class="goods-price">原价: ¥{{ props.row.good?.price || '0.00' }}</p>
                        <p class="goods-category">{{ props.row.good?.category || '无分类' }}</p>
                        <p class="goods-desc-text">{{ props.row.good?.description || '暂无描述' }}</p>
                      </div>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="买家信息">
                    <div class="user-info">
                      <span>{{ props.row.buyer?.nickname || '未知用户' }}</span>
                      <span class="user-id">(ID: {{ props.row.buyer_id || '未知' }})</span>
                      <div class="user-contact" v-if="props.row.buyer?.phone">
                        📞 {{ props.row.buyer.phone }}
                      </div>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="卖家信息">
                    <div class="user-info">
                      <span>{{ props.row.seller?.nickname || '未知用户' }}</span>
                      <span class="user-id">(ID: {{ props.row.seller_id || '未知' }})</span>
                      <div class="user-contact" v-if="props.row.seller?.phone">
                        📞 {{ props.row.seller.phone }}
                      </div>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="订单金额">
                    <span class="amount">¥{{ props.row.amount }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="创建时间">
                    {{ formatDate(props.row.created_at) }}
                  </el-descriptions-item>
                  <el-descriptions-item label="更新时间">
                    {{ formatDate(props.row.updated_at) }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="order_id" label="订单ID" width="80" align="center" />
          <el-table-column label="商品" min-width="200">
            <template #default="scope">
              <div class="goods-cell">
                <el-image 
                  v-if="getGoodsImage(scope.row.good)"
                  :src="getGoodsImage(scope.row.good)" 
                  alt="商品图片"
                  class="goods-thumb"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-error-small">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="goods-info-compact">
                  <span class="goods-title">{{ scope.row.good?.title || '未知商品' }}</span>
                  <span class="goods-original-price">原价: ¥{{ scope.row.good?.price || '0.00' }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="买家" width="120">
            <template #default="scope">
              <div class="user-cell">
                {{ scope.row.buyer?.nickname || '未知用户' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="卖家" width="120">
            <template #default="scope">
              <div class="user-cell">
                {{ scope.row.seller?.nickname || '未知用户' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100" align="center">
            <template #default="scope">
              <span class="amount">¥{{ scope.row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                :type="getStatusType(scope.row.status)"
                size="small"
                effect="light"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160">
            <template #default="scope">
              <div class="time-cell">
                {{ formatDate(scope.row.created_at) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  v-if="scope.row.status === 1"
                  type="success"
                  size="small"
                  :icon="Check"
                  @click="handleApprove(scope.row)"
                >
                  通过
                </el-button>
                <el-button
                  v-if="scope.row.status === 1"
                  type="danger"
                  size="small"
                  :icon="Close"
                  @click="handleReject(scope.row)"
                >
                  拒绝
                </el-button>
                <el-tag v-else type="info" size="small">无需操作</el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Check, Close, RefreshLeft, Picture } from '@element-plus/icons-vue'
import { orderApi } from '@/api/order'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const orderList = ref([])

const searchForm = reactive({
  keyword: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 方法
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...buildSearchParams()
    }

    console.log('请求参数:', params)

    // 使用search接口获取订单列表
    let response
    if (orderApi.search) {
      response = await orderApi.search(params)
    } else {
      response = await orderApi.list(params)
    }

    if (response.code === 0) {
      orderList.value = response.data.list || response.data || []
      pagination.total = response.data.pagination?.total || response.data.total || 0
      console.log('获取订单成功:', orderList.value)
    } else {
      ElMessage.error(response.msg || '获取订单列表失败')
      orderList.value = []
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    // 如果API调用失败，使用模拟数据
    await loadMockData()
  } finally {
    loading.value = false
  }
}

// 模拟数据加载
const loadMockData = async () => {
  try {
    const mockData = {
      code: 0,
      data: {
        list: [
          {
            order_id: 1001,
            buyer_id: 1,
            seller_id: 2,
            goods_id: 101,
            amount: '299.00',
            status: 1,
            created_at: '2024-01-15 10:30:00',
            updated_at: '2024-01-15 10:30:00',
            buyer: {
              user_id: 1,
              nickname: '测试买家',
              phone: '138****1234'
            },
            seller: {
              user_id: 2,
              nickname: '测试卖家',
              phone: '139****5678'
            },
            good: {
              item_id: 101,
              title: 'MacBook Pro 2023',
              price: '299.00',
              description: '几乎全新的MacBook Pro，配置齐全',
              category: '电子产品',
              images: '/images/macbook.jpg'
            }
          },
          {
            order_id: 1002,
            buyer_id: 3,
            seller_id: 4,
            goods_id: 102,
            amount: '150.00',
            status: 2,
            created_at: '2024-01-14 15:20:00',
            updated_at: '2024-01-14 16:30:00',
            buyer: {
              user_id: 3,
              nickname: '买家二号'
            },
            seller: {
              user_id: 4,
              nickname: '卖家二号'
            },
            good: {
              item_id: 102,
              title: '二手书籍-计算机科学',
              price: '150.00',
              description: '大学计算机科学教材，保存完好',
              category: '图书',
              images: '/images/book.jpg'
            }
          }
        ],
        pagination: {
          total: 2,
          page: 1,
          pageSize: 10,
          totalPages: 1
        }
      },
      msg: 'success'
    }

    orderList.value = mockData.data.list
    pagination.total = mockData.data.pagination.total
    ElMessage.warning('使用模拟数据，请检查API接口')
  } catch (error) {
    ElMessage.error('加载数据失败: ' + error.message)
    orderList.value = []
  }
}

const buildSearchParams = () => {
  const params = {}
  
  // 关键词搜索
  if (searchForm.keyword) {
    params.keyword = searchForm.keyword
  }

  // 状态筛选
  if (searchForm.status !== '') {
    params.status = searchForm.status
  }

  console.log('构建的搜索参数:', params)
  return params
}

const handleSearch = () => {
  pagination.page = 1
  loadOrders()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: ''
  })
  pagination.page = 1
  loadOrders()
}

const handleBack = () => {
  router.push('/admin/dashboard')
}

const handleApprove = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要通过订单 ${order.order_id} 的审核吗？`,
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await orderApi.updateStatus(order.order_id, { status: 2 })
    
    if (response.code === 0) {
      ElMessage.success('订单审核通过')
      loadOrders()
    } else {
      ElMessage.error(response.msg || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核操作失败:', error)
      ElMessage.error('审核操作失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

const handleReject = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要拒绝订单 ${order.order_id} 的审核吗？拒绝后订单将变为已取消状态。`,
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await orderApi.updateStatus(order.order_id, { status: 0 })
    
    if (response.code === 0) {
      ElMessage.success('订单审核不通过，订单已取消')
      loadOrders()
    } else {
      ElMessage.error(response.msg || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核操作失败:', error)
      ElMessage.error('审核操作失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

const getStatusText = (status) => {
  const statusMap = {
    0: '审核不通过',
    1: '待审核',
    2: '审核通过',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'warning',
    2: 'success',
    3: 'info',
    4: 'info'
  }
  return typeMap[status] || 'info'
}

const getGoodsImage = (good) => {
  if (!good || !good.images) return null
  
  try {
    const images = typeof good.images === 'string' ? good.images.split(',') : good.images
    const firstImage = images[0]?.trim()
    
    if (!firstImage) return null
    
    // 处理图片URL
    if (firstImage.startsWith('http')) {
      return firstImage
    } else if (firstImage.startsWith('/')) {
      // 如果是相对路径，添加基础URL
      return `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001'}${firstImage}`
    } else {
      // 其他情况直接返回
      return firstImage
    }
  } catch (error) {
    console.error('处理商品图片出错:', error)
    return null
  }
}

const getGoodsPreviewImages = (good) => {
  if (!good || !good.images) return []
  
  try {
    const images = typeof good.images === 'string' ? good.images.split(',') : good.images
    return images.map(img => {
      const trimmedImg = img.trim()
      if (trimmedImg.startsWith('http')) {
        return trimmedImg
      } else if (trimmedImg.startsWith('/')) {
        return `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001'}${trimmedImg}`
      } else {
        return trimmedImg
      }
    }).filter(img => img)
  } catch (error) {
    console.error('处理商品预览图片出错:', error)
    return []
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadOrders()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadOrders()
}

// 生命周期
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.market-manage {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-filter-row {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  margin-top: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.order-detail {
  padding: 16px;
}

.goods-info {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.goods-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  flex-shrink: 0;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.goods-desc {
  flex: 1;
}

.goods-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
  margin: 8px 0;
}

.goods-category {
  color: #909399;
  font-size: 12px;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.goods-desc-text {
  color: #606266;
  font-size: 13px;
  margin-top: 8px;
  line-height: 1.4;
}

.user-info {
  line-height: 1.5;
}

.user-id {
  color: #909399;
  font-size: 12px;
}

.user-contact {
  color: #409EFF;
  font-size: 12px;
  margin-top: 4px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.goods-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.goods-thumb {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  flex-shrink: 0;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.goods-info-compact {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.goods-title {
  font-weight: 500;
  line-height: 1.4;
}

.goods-original-price {
  color: #909399;
  font-size: 12px;
}

.user-cell {
  line-height: 1.4;
}

.time-cell {
  font-size: 12px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  height: 100%;
}

.image-error-small {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  height: 100%;
}

:deep(.el-table__expanded-cell) {
  background: #fafafa;
}

:deep(.el-descriptions__body) {
  background: #fafafa;
}

:deep(.el-card__header) {
  padding-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    gap: 8px;
  }
}
</style>